package meta

import (
	"fmt"

	"gitee.com/micro-plat/codeless/apiserver/meta/biz/meta"
	"github.com/micro-plat/hydra"
)

func AddMetaTableHandle(ctx hydra.IContext) interface{} {
	if err := ctx.Request().Check("title", "name", "columns"); err != nil {
		return err
	}
	tenantID := ctx.Request().GetInt("tenant_id")
	title := ctx.Request().GetString("title")
	tableName := ctx.Request().GetString("name")
	description := ctx.Request().GetString("description")
	tableName = fmt.Sprintf("%s_%d", tableName, tenantID)

	// 表数据保存到元数据表
	columns := ctx.Request().GetArray("columns")
	table, err := meta.AddMetaTable(tenantID, title, tableName, description, columns)
	if err != nil {
		return err
	}
	return table
}

func GetTablesHandle(ctx hydra.IContext) interface{} {
	tenantID := ctx.Request().GetInt("tenant_id")
	tableName := ctx.Request().GetString("name")
	tableId := ctx.Request().GetInt64("table_id")
	metaTable, err := meta.GetMetaTables(tenantID, tableName, tableId)
	if err != nil {
		return err
	}
	return metaTable
}

// UpdateMetaTableHandle 更新元表处理函数
func UpdateMetaTableHandle(ctx hydra.IContext) interface{} {
	tableID := ctx.Request().GetInt64("table_id")
	tenantID := ctx.Request().GetInt("tenant_id")
	title := ctx.Request().GetString("title")
	description := ctx.Request().GetString("description")

	metaTable, err := meta.UpdateMetaTable(tenantID, tableID, title, description)
	if err != nil {
		return err
	}

	return metaTable
}
